<template>
    <div class="detail-container">
        <el-card shadow="never" style="margin-top: 15px;" class="detail-form">
            <el-form  size="mini" label-width="150px" style="margin-top:20px" ref="form" :rules="rules" :model="form">
                    <div style="margin-top:20px">
                        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                        <span class="font-small">基本信息</span>
                    </div>

                    <el-form-item label="采购合同：" style="margin-top:20px;margin-bottom:20px;">
                        <el-input style="width:200px" @change="getPumsOrderInfo" v-model.trim="form.purchaseOrderSn"></el-input>
                    </el-form-item>

                    <el-form-item label="供应商：" style="margin-bottom:20px;" prop="supplierName">
                        <el-input style="width:200px" v-model="form.supplierName"></el-input>
                    </el-form-item>

                    <el-form-item label="合同公司：" style="margin-bottom:20px;" prop="fromCompany">
                          <el-select v-model="form.fromCompany">
                              <el-option value="常州普利成" label="常州普利成" key="常州普利成"></el-option>
                              <el-option value="塑盟科技集团有限公司" label="塑盟科技集团有限公司" key="塑盟科技集团有限公司"></el-option>
                              <el-option value="上海泛塑" label="上海泛塑" key="上海泛塑"></el-option>
                              <el-option value="华灯车尚" label="华灯车尚" key="华灯车尚"></el-option>
                          </el-select>
                    </el-form-item>

                    <el-form-item label="提货日期：" style="margin-bottom:20px;" prop="tOrderTime">
                        <el-date-picker
                                v-model="form.tOrderTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="选择日期时间">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="提货备注：" style="margin-bottom:20px;">
                        <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" style="width:300px" v-model.trim="form.tRemark"></el-input>
                    </el-form-item>
                    <div style="margin-top: 20px;clear: both">
                        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                        <span class="font-small">商品信息</span>
                    </div>
                    <el-table
                            ref="orderItemTable"
                            :data="form.ordGoodsList"
                            style="margin-top: 20px;box-sizing: border-box;width:1171px" border>
                        <el-table-column label="商品名称" width="200">
                            <template slot-scope="scope">
                                <el-form-item label-width="0" :prop="`ordGoodsList.${scope.$index}.goodsKingId`" :rules="rules.goodsKingId">
                                    <el-select
                                            v-model="scope.row.goodsKingId"
                                            clearable
                                            filterable
                                            remote
                                            reserve-keyword
                                            placeholder="请输入关键词"
                                            :remote-method="((val)=>{remoteMethod(val, scope.$index)})"
                                            :loading="scope.row.loading">
                                        <el-option
                                                v-for="item in scope.row.options"
                                                :key="item.kingId"
                                                :label="item.goodsSn"
                                                :value="item.kingId">
                                        </el-option>
                                    </el-select>
                                </el-form-item>

                            </template>
                        </el-table-column>
                        <el-table-column label="包装" width="180"  align="center">
                            <template slot-scope="scope">
                                <el-form-item label-width="0">
                                    <el-input-number v-model="scope.row.goodsWeight" :controls="false" :precision="0" class="inputleft" style="width:100px"></el-input-number>
                                    <span>kg/包</span>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="采购数量（吨）" width="130" align="center">
                            <template slot-scope="scope">
                                <el-form-item label-width="0">
                                    {{scope.row.purchaseNum}}
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="提货数量（吨）" width="130" align="center">
                            <template slot-scope="scope">
                                <el-form-item label-width="0" :prop="`ordGoodsList.${scope.$index}.takeNum`" :rules="rules.takeNum">
                                    <el-input-number v-model="scope.row.takeNum" controls-position="right" style="width:100px" :min="0" :controls="false"></el-input-number>
                                </el-form-item>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否含托盘" width="130" align="center">
                            <template slot-scope="scope">
                                <el-form-item label-width="0">
                                    <el-checkbox v-model="scope.row.isHasTray">是</el-checkbox>
                                </el-form-item>

                            </template>
                        </el-table-column>
                        <el-table-column label="备注" width="300" align="center">
                            <template slot-scope="scope">
                                <el-form-item label-width="0">
                                    <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" style="width:250px"  v-model.trim="scope.row.tgRemark"></el-input>
                                </el-form-item>

                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" @click="delItem(scope.$index)">删除</el-button>
                            </template>
                        </el-table-column>

                    </el-table>
                    <div style="margin-top:10px;">
                        <el-button size="mini" @click="addGoodsItem">添加商品</el-button>
                    </div>

                    <div style="margin-top: 40px;clear: both">
                        <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                        <span class="font-small">提货流向</span>
                    </div>

                    <el-form-item label-width="0" style="margin-top:20px;">
                        <el-radio-group v-model="form.flowTo">
                            <el-radio :label="1">客户</el-radio>
                            <el-radio :label="2">仓库</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <div style="overflow: hidden" v-if="form.flowTo == 1">
                        <div style="margin-top: 40px;clear: both">
                            <svg-icon icon-class="marker" style="color: #606266"></svg-icon>
                            <span class="font-small">销售合同</span>
                        </div>
                            <el-form-item label="合同号：" style="margin-bottom:20px;">
                                <el-input style="width:200px" @change="getOrderInfo" v-model.trim="form2.saleOrderSn"></el-input>
                                <el-button type="text" style="margin-left:10px" v-if="form2.saleOrderId" @click="toDetail">查看合同详情</el-button>
                                <el-button type="text" style="margin-left:10px"  @click="showKeHu">搜索</el-button>
                            </el-form-item>
                         <div v-if="form2.saleOrderId">
                             <el-form-item label="客户名称：" style="margin-bottom:20px;">{{form2.customerName}}</el-form-item>
                             <el-form-item label="合同时间：" style="margin-bottom:20px;">{{form2.createTime}}</el-form-item>
                             <el-form-item label="付款状态：" style="margin-bottom:20px;">{{form2.payState | fiferPayState}}</el-form-item>
                             <el-form-item label="财务审核状态：" style="margin-bottom:20px;">{{form2.financeState}}</el-form-item>
                             <el-form-item label="收货信息：" style="margin-bottom:20px;">
                                 {{form2.receiverName}} <span style="padding-left:10px">{{form2.receiverMobile}}</span><span style="padding-left:10px">{{form2.addressInfo}}</span>
                             </el-form-item>
                             <el-form-item label="商品信息：" style="margin-bottom:20px;">
                                 <el-table
                                         :data="form2.ordGoodsList"
                                         style="box-sizing: border-box;width:691px" border>
                                     <el-table-column label="商品名称" width="200">
                                         <template slot-scope="scope">
                                             {{scope.row.goodsName}}/{{scope.row.goodsSn}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="合同数量" width="100"  align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.buyNum}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="已发货数量" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.sendNum}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="期望发货时间" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.expectSendDate}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="预计发货时间" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.sendDate1}}
                                         </template>
                                     </el-table-column>
                                 </el-table>
                             </el-form-item>
                             <el-form-item label="排货信息：" style="margin-bottom:20px;">
                                 <el-table
                                         :data="form2.planList"
                                         style="box-sizing: border-box;width:871px" border>
                                     <el-table-column label="商品名称" width="200">
                                         <template slot-scope="scope">
                                             {{scope.row.goodsName}}/{{scope.row.goodsSn}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="提货数量" width="100"  align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.planNum}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="提货仓库" width="180" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.planWarehouse}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="提货时间" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.takeTime}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="联系人" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.contactName}}
                                         </template>
                                     </el-table-column>
                                     <el-table-column label="联系电话" width="130" align="center">
                                         <template slot-scope="scope">
                                             {{scope.row.contactMobile}}
                                         </template>
                                     </el-table-column>
                                 </el-table>
                             </el-form-item>
                         </div>
                    </div>

                   <div v-if="form.flowTo == 2">
                    <el-form-item label="仓库地址：" style="margin-bottom:20px;">
                        <el-select v-model="form.toWarehouse">
                            <el-option value="江苏一号仓" label="江苏一号仓" key="江苏一号仓"></el-option>
                            <el-option value="余达仓" label="余达仓" key="余达仓"></el-option>
                            <el-option value="塑通仓" label="塑通仓" key="塑通仓"></el-option>
                        </el-select>
                    </el-form-item>
                </div>
            </el-form>
        </el-card>

        <div style="margin-top:40px;text-align: center">
            <el-button style="width:150px;" @click="submit" type="primary" :loading="btnLoading">提交</el-button>
        </div>


        <!--批量新增-->
        <el-dialog
                title="选择客户"
                :close-on-click-modal="false"
                :visible.sync="dialogVisible2"
                width="900px">
            <div>
                <el-form size="mini"  ref="paramsForm" :model="params" :inline="true">
                    <el-form-item label-width="80" label="合同号" prop="customerId">
                        <el-input v-model="params.orderSn"></el-input>
                    </el-form-item>
                    <el-form-item label-width="80" label="客户名称" prop="customerId">
                        <el-select
                                clearable
                                v-model="params.customerId"
                                filterable
                                remote
                                reserve-keyword
                                placeholder="请输入关键词"
                                :remote-method="((val)=>{remoteMethod1(val, 1)})"
                                :loading="customerLoading1">
                            <el-option
                                    v-for="item in customerList1"
                                    :key="item.customerId"
                                    :label="item.customerName"
                                    :value="item.customerId">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="searchOrder">查询</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="ordGoodsList" border
                          highlight-current-row
                          @current-change="handleCurrentChange"
                          style="width:99%">
                    <el-table-column
                            align="center"
                            label="合同号"
                            min-width="150">
                        <template slot-scope="scope">
                                {{scope.row.orderSn}}
                        </template>
                    </el-table-column>

                    <el-table-column
                            align="center"
                            label="客户名称"
                            min-width="200">
                        <template slot-scope="scope">
                            {{scope.row.customerName}}
                        </template>
                    </el-table-column>

                    <el-table-column
                            align="center"
                            label="合同商品"
                            min-width="200">
                        <template slot-scope="scope">
                            {{scope.row.goodsName}}/{{scope.row.goodsSn}}
                        </template>
                    </el-table-column>

                    <el-table-column
                            align="center"
                            label="合同数量"
                            min-width="100">
                        <template slot-scope="scope">
                            {{scope.row.goodsNum}}
                        </template>
                    </el-table-column>
                </el-table>
                <div class="pagination-container">
                    <el-pagination
                            background
                            @size-change="handleSizeChangeOrder"
                            @current-change="handleCurrentChangeOrder"
                            layout="total, sizes,prev, pager, next,jumper"
                            :current-page.sync="params.pageNum"
                            :page-size="params.pageSize"
                            :page-sizes="[10,15,20]"
                            :total="orderCount">
                    </el-pagination>
                </div>
                <div style="clear: both"></div>
                <div slot="footer" class="dialog-footer" style="text-align: right;margin-top:10px">
                    <el-button @click="handleClose2" size="small">取 消</el-button>
                    <el-button type="primary" @click="handleConfirm2" size="small">确 定</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex'
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import {purchaseOrderInfo,saleOrderInfo,addOrderTakeOrder,getCustomerOption,getOrderGoodsOfTakeOrder,deliverDeliverSet,deliverDeliverList,getOrderUsersList,deliverUpdate,deliverUpdatePrintNum} from '@/api/partner'
    import {goodsList} from '@/api/company'
    import {validateCommission} from '@/utils/validate';
    const defaultForm={
        "purchaseOrderId": null,
        "purchaseOrderSn": "",
        "supplierName": "",
        "fromCompany": "",
        "ordGoodsList": [],
        tRemark:'原厂正牌，原料生产日期不超过合同签订日前六个月，外观无破损、潮湿，无大面积污渍，包装袋规格及颜色一致。',
        saleOrderId:null,
        flowTo:1,
        toWarehouse:'',
    };
    const defaultItme = {
        "goodsKingId": '',
        "goodsName": "",
        "goodsSn": "",
        "purchaseNum": "",
        goodsWeight:'',
        takeNum:'',
        isHasTray:false,
        tgRemark:'',
        options:[],
        loading:false,
    };
    const defaultForm2={
        "saleOrderId": null,
        "saleOrderSn": "",
        "customerName": "",
        "createTime": "",
        "payState": '',
        "financeState": "",
        "receiverName": "",
        "receiverMobile": "",
        "addressInfo": "",
        "ordGoodsList": [],
        planList:[]
    };
    export default {
        name: "customerDetail",
        data(){
            const isvalidateCommission = (rule, value, callback) => {
                if (!validateCommission(parseFloat(value))) {
                    callback(new Error('非负整数或小数'))
                } else if(value > 99999999){
                    callback(new Error('最大值为99999999'))
                }else {
                    callback()
                }
            };
            return{
                loading:false,
                deliverId:this.$route.query.id,
                orderInfo:{},
                dialogVisible:false,
                btnLoading:false,
                form:JSON.parse(JSON.stringify(defaultForm)),
                form2:JSON.parse(JSON.stringify(defaultForm2)),
                rules:{
                    supplierName:[{required: true, trigger: 'blur' ,message: '此项必填',}],
                    fromCompany:[{required: true, trigger: 'blur' ,message: '此项必填',}],
                    tOrderTime:[{required: true, trigger: 'blur' ,message: '此项必填',}],
                    goodsKingId:[{required: true, trigger: 'blur' ,message: '此项必填',}],
                    takeNum:[{required: true, trigger: 'blur' ,message: '此项必填',}],
                },
                dialogVisible2:false,
                customerLoading1:false,
                customerList1:[],
                ordGoodsList:[],
                orderCount:0,
                params:{
                    customerId:'',
                    orderSn:'',
                    pageNum: 1,
                    pageSize: 10,

                },
                currentRow:{}
            }
        },
        computed: {
            ...mapGetters([
                'name',
                'mobile',
                'userId'
            ]),
        },
        created() {
            if(this.$route.query.purchaseOrderSn){
                this.form.purchaseOrderSn = this.$route.query.purchaseOrderSn;
                this.getPumsOrderInfo()
            }
            // this.getUserOptionList();
        },
        filters: {
            fiferPayState(val){
                if(val == 0){
                    return '--'
                }else if(val == 1){
                    return '未结清'
                }else if(val == 2){
                    return '已结清'
                }
            },
        },
        methods:{
            //查询销售订单
            searchOrder(){
                this.params.pageNum = 1;
                this.getListData();
            },
            handleSizeChangeOrder(val){
                this.params.pageNum = 1;
                this.params.pageSize = val;
                this.getListData();
            },
            handleCurrentChangeOrder(val){
                this.params.pageNum = val;
                this.getListData();
            },
            getListData(){
                getOrderGoodsOfTakeOrder(this.params).then((res)=>{
                    this.ordGoodsList = res.list;
                    this.orderCount = res.count
                })
            },
            //显示客户搜索
            showKeHu(){
                this.dialogVisible2 = true;
            },
            handleClose2(){
                this.dialogVisible2 = false;
            },
            handleConfirm2(){
                this.form2.saleOrderSn = this.currentRow.orderSn;
                this.getOrderInfo();
                this.handleClose2();

            },
            handleCurrentChange(val) {
                this.currentRow = val;
            },
            //获取客户列表
            remoteMethod1(query,key) {
                if(query && query!= '') {
                    this['customerLoading'+key] = true;
                    getCustomerOption({keywords: query}).then(response => {
                        this['customerList'+key] = response;
                        this['customerLoading'+key] = false;
                    }).catch(() => {
                        this['customerLoading'+key] = false;
                    });
                }
            },

            //去详情页
            toDetail(){
                let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:this.form2.saleOrderId,type:'see'}});
                window.open(routeData.href);
            },
            delItem(index){
                this.form.ordGoodsList.splice(index,1)
            },
            addGoodsItem(){
                this.form.ordGoodsList.push(defaultItme)
            },
            remoteMethod(key, index) {
                this.form['ordGoodsList'][index]['loading'] = true;
                goodsList({keyword: key}).then((res) => {
                    this.form['ordGoodsList'][index]['options'] = res.list;
                    this.form['ordGoodsList'][index]['loading'] = false;
                }).catch(() => {
                    this.form['ordGoodsList'][index]['loading'] = false;
                })
            },

            //获取员工下拉选项
            getUserOptionList(){
                getOrderUsersList({type:'物流'}).then((res)=>{
                    this.userOptionList = res;
                })
            },

            //获取订单合同详情
            getOrderInfo(){
                let saleOrderSn = this.form2.saleOrderSn;
                this.form2 = JSON.parse(JSON.stringify(defaultForm2));
                saleOrderInfo({saleOrderSn:saleOrderSn}).then((res)=>{
                    this.form.saleOrderId = res.saleOrderId;
                    this.form2.saleOrderId = res.saleOrderId;
                    this.form2.saleOrderSn = res.saleOrderSn;
                    this.form2.customerName = res.customerName;
                    this.form2.createTime = res.createTime;
                    this.form2.payState = res.payState;
                    this.form2.financeState = res.financeState;
                    this.form2.receiverName = res.receiverName;
                    this.form2.receiverMobile = res.receiverMobile;
                    this.form2.addressInfo = res.addressInfo;
                    this.form2.ordGoodsList = res.ordGoodsList;
                    this.form2.planList = res.planList;
                }).catch((err)=>{
                    this.form2.saleOrderSn = saleOrderSn;
                })
            },
            //获取采购订单详情
            getPumsOrderInfo(){
                let purchaseOrderSn = this.form.purchaseOrderSn;
                this.form = JSON.parse(JSON.stringify(defaultForm));
                purchaseOrderInfo({purchaseOrderSn:purchaseOrderSn}).then((res)=>{
                        this.form.purchaseOrderSn = res.purchaseOrderSn;
                        this.form.purchaseOrderId = res.purchaseOrderId;
                        this.form.supplierName = res.supplierName;
                        this.form.fromCompany = res.fromCompany;
                        this.form.ordGoodsList = [];
                        res.ordGoodsList.forEach((el,index)=>{
                            this.form.ordGoodsList.push({
                                goodsKingId:el.goodsKingId,
                                goodsWeight:'',
                                purchaseNum:el.purchaseNum,
                                takeNum:el.unTakeNum,
                                isHasTray:false,
                                tgRemark:'',
                            });
                            this.form.ordGoodsList[index]['options'] = [];
                            this.form.ordGoodsList[index]['options'].push({kingId:el.goodsKingId,goodsSn:el.goodsSn})
                        })
                }).catch((err)=>{
                    this.form.purchaseOrderSn = purchaseOrderSn;
                })
            },

            //提交
            submit(){
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.btnLoading = true;
                        let data = {};
                        data.tOrderTime = this.form.tOrderTime;
                        data.purchaseOrderId = this.form.purchaseOrderId ? this.form.purchaseOrderId : '';
                        data.fromCompany = this.form.fromCompany;
                        data.supplierName = this.form.supplierName;
                        data.tRemark = this.form.tRemark;
                        data.flowTo = this.form.flowTo;
                        console.log(data.flowTo)
                        if(data.flowTo == 1 ){
                            data.saleOrderId = this.form2.saleOrderId ? this.form2.saleOrderId : '';
                        }else if(data.flowTo == 2){
                            console.log("this.form.toWarehouse",this.form.toWarehouse)
                            data.toWarehouse = this.form.toWarehouse;
                        }
                        data.ordGoodsList = [];
                        this.form.ordGoodsList.forEach((el)=>{
                            data.ordGoodsList.push({
                                goodsKingId:el.goodsKingId,
                                takeNum:el.takeNum,
                                isHasTray:el.isHasTray ? 1 : 0,
                                goodsWeight:el.goodsWeight,
                                tgRemark:el.tgRemark
                            })
                        });
                        addOrderTakeOrder(data).then(response => {
                            this.btnLoading = false;
                            this.$message({
                                message: '提交成功',
                                type: 'success',
                                duration: 1000
                            });
                            this.$router.push({name:'pickUpList'});
                        }).catch(() => {
                            this.btnLoading = false;
                        })
                    }
                })
            },
        }
    }
</script>

<style  lang="scss" scoped>
    .avatar-uploader{
        margin-bottom:10px;
        display: inline-block;
        width:80px;
        height:80px;
        border:1px solid #DCDFE6;
        text-align: center;
        line-height: 80px;
    }
    .detail-form{
        .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
            margin-bottom:0px;
        }
    }

    .detail-container {
        width: 90%;
        padding: 20px 20px 20px 20px;
        margin: 20px auto;
        .el-card__header{
            background: #f8f8f8;
            .kehu-name{
                display: inline-block;
                font-size:14px;
                vertical-align: middle;
            }
            .kehu-label{
                font-size:12px;
                vertical-align: middle;
                display: inline-block;
                margin-left:15px;
                color: #409eff;
                background: #ecf5ff;
                border: 1px solid #b3d8ff;
                height:24px;
                line-height: 24px;
                padding:0 10px;
                border-radius: 5px;
            }
            .kehu-info{
                text-align: right;
                font-size: 12px;
                color:#333;
                line-height: 20px;
                span{
                    padding-left:16px;
                }
            }
        }
        .operate-container {
            background: #F2F6FC;
            height: 80px;
            margin: -20px -20px 0;
            line-height: 80px;
        }
    }
    .price-block{
        font-size:12px;
        line-height:30px;
        .lab{
            display: inline-block;
            width:100px;
            text-align: right;
        }
        .text{
            display: inline-block;
        }
    }
    #print-div{
        font-size:14px;
        font-family: "Microsoft YaHei";
        color:#000;
        .title{
            font-size:28px;
            font-weight: bold;
            text-align: center;
            line-height: 40px;
        }
        .paper-top{
            margin-top:20px;
            line-height: 20px;
        }
        .good-table{
            margin-top:0px;
            table{
                border-left:1px solid #000;
                border-bottom:1px solid #000;
                td,th{
                    font-weight: normal;
                    border-right:1px solid #000;
                    border-top:1px solid #000;
                    padding:5px 10px;
                    line-height: 20px;
                }
            }
        }
        .paper-bottom{
            margin-top:0px;
            line-height: 20px;
        }
    }
</style>
